import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
    state: () => ({
        userInfo: {
            user_name: '',
            email: '',
            account: '',
            avatar: '',
            location: '',
            introduction: '',
            score: 0,
            gender: ''
        },
        isLoggedIn: false,
        orders: [],
        orderLoading: false,
        aiAuth:'Bearer sk-242f443672eb4fd99a61d7abbf16a5ef'
    }),
    
    actions: {
        // 更新用户信息
        updateUserInfo(info) {
            this.userInfo = { ...this.userInfo, ...info };
            this.isLoggedIn = true;
            // 持久化存储
            uni.setStorageSync('userInfo', this.userInfo);
            uni.setStorageSync('isLoggedIn', true);
        },
        
        // 清除用户信息
        clearUserInfo() {
            this.userInfo = {
                user_name: '',
                email: '',
                account: '',
                avatar: '',
                location: '',
                introduction: '',
                score: 0,
                gender: ''
            };
            this.isLoggedIn = false;
            uni.removeStorageSync('userInfo');
            uni.removeStorageSync('isLoggedIn');
        },
        
        // 积分相关操作
        async addScore(points) {
            return this.updateUserScore(points);
        },
        
        // 初始化store
        initStore() {
            const userInfo = uni.getStorageSync('userInfo');
            const isLoggedIn = uni.getStorageSync('isLoggedIn');
            if (userInfo) {
                this.userInfo = userInfo;
                this.isLoggedIn = isLoggedIn;
            }
        },
        
        // 设置用户信息
        setUserInfo(userInfo) {
            console.log("设置用户信息:", userInfo);
            
            // 处理字段名称不一致的情况
            const normalizedUserInfo = { ...userInfo };
            
            // 如果有score字段但没有core字段，则添加core字段
            if (normalizedUserInfo.score !== undefined && normalizedUserInfo.core === undefined) {
                normalizedUserInfo.core = normalizedUserInfo.score;
            }
            
            // 如果有core字段但没有score字段，则添加score字段
            if (normalizedUserInfo.core !== undefined && normalizedUserInfo.score === undefined) {
                normalizedUserInfo.score = normalizedUserInfo.core;
            }
            
            // 确保store中的用户信息保持完整结构
            this.userInfo = {
                ...this.userInfo,
                ...normalizedUserInfo
            };
            this.isLoggedIn = true;
            
            // 打印更新后的数据，确保正确
            console.log("更新后的store数据:", this.userInfo);
            
            // 保存到本地存储
            uni.setStorageSync('userInfo', this.userInfo);
            uni.setStorageSync('isLoggedIn', true);
        },
        
        // 更新用户信息到本地，但不调用云函数
        updateUserInfoLocal(data) {
            if (!this.userInfo) {
                this.userInfo = data;
            } else {
                this.userInfo = {
                    ...this.userInfo,
                    ...data
                };
            }
            
            // 保存到本地存储
            uni.setStorageSync('userInfo', this.userInfo);
        },
        
        // 设置临时用户信息，不改变登录状态
        setTempUserInfo(userInfo) {
            console.log("设置临时用户信息:", userInfo);
            
            // 只更新本地数据，不更改登录状态
            this.userInfo = userInfo;
            
            // 不保存到本地存储
            console.log("临时用户数据已设置:", this.userInfo);
        },
        
        // 更新用户积分的方法
        async updateUserScore(points) {
            try {
                if (!this.userInfo) {
                    console.error("用户未登录或信息不完整");
                    return false;
                }
                
                // 计算新积分值
                const newScore = (this.userInfo.score || 0) + points;
                
                // 更新本地状态
                this.userInfo.score = newScore;
                
                // 调用云函数更新数据库
                const result = await uniCloud.callFunction({
                    name: "updateUserInfo",
                    data: {
                        body: JSON.stringify({
                            action: "updateUser",
                            account: this.userInfo.account,
                            score: newScore
                        })
                    }
                });
                
                if (result.result && result.result.status === 1) {
                    // 更新成功，保存到本地存储
                    uni.setStorageSync('userInfo', this.userInfo);
                    return true;
                }
                
                console.error("更新积分失败:", result.result?.message);
                return false;
            } catch (error) {
                console.error("更新积分失败:", error);
                return false;
            }
        },
        
        // 获取用户所有订单
        async fetchOrders() {
            if (!this.isLoggedIn || !this.userInfo || !this.userInfo.account) {
                console.error('用户未登录，无法获取订单');
                return false;
            }
            
            this.orderLoading = true;
            
            try {
                const result = await uniCloud.callFunction({
                    name: 'orderManage',
                    data: {
                        body: JSON.stringify({
                            action: 'getAll',
                            account: this.userInfo.account
                        })
                    }
                });
                
                if (result.result && result.result.status === 1) {
                    this.orders = result.result.data;
                    return true;
                } else {
                    console.error('获取订单失败:', result.result?.message);
                    return false;
                }
            } catch (error) {
                console.error('获取订单异常:', error);
                return false;
            } finally {
                this.orderLoading = false;
            }
        },
        
        // 创建新订单
        async createOrder(orderData) {
            if (!this.isLoggedIn || !this.userInfo || !this.userInfo.account) {
                uni.showToast({
                    title: '请先登录',
                    icon: 'none'
                });
                return false;
            }
            
            try {
                const result = await uniCloud.callFunction({
                    name: 'orderManage',
                    data: {
                        body: JSON.stringify({
                            action: 'create',
                            account: this.userInfo.account,
                            orderData
                        })
                    }
                });
                
                if (result.result && result.result.status === 1) {
                    // 更新本地订单列表
                    this.orders.unshift(result.result.data);
                    return result.result.data;
                } else {
                    uni.showToast({
                        title: result.result?.message || '创建订单失败',
                        icon: 'none'
                    });
                    return false;
                }
            } catch (error) {
                console.error('创建订单异常:', error);
                uni.showToast({
                    title: '创建订单失败',
                    icon: 'none'
                });
                return false;
            }
        },
        
        // 更新订单状态
        async updateOrderStatus(orderId, status) {
            try {
                const result = await uniCloud.callFunction({
                    name: 'orderManage',
                    data: {
                        body: JSON.stringify({
                            action: 'update',
                            orderId,
                            orderData: { status }
                        })
                    }
                });
                
                if (result.result && result.result.status === 1) {
                    // 更新本地订单状态
                    const orderIndex = this.orders.findIndex(order => order._id === orderId);
                    if (orderIndex !== -1) {
                        this.orders[orderIndex].status = status;
                        this.orders[orderIndex].update_time = Date.now();
                    }
                    return true;
                } else {
                    uni.showToast({
                        title: result.result?.message || '更新订单失败',
                        icon: 'none'
                    });
                    return false;
                }
            } catch (error) {
                console.error('更新订单异常:', error);
                uni.showToast({
                    title: '更新订单失败',
                    icon: 'none'
                });
                return false;
            }
        },
        
        // 根据状态获取订单
        async getOrdersByStatus(status) {
            if (!this.isLoggedIn || !this.userInfo || !this.userInfo.account) {
                console.error('用户未登录，无法获取订单');
                return [];
            }
            
            try {
                console.log('获取特定状态订单:', status);
                console.log('当前用户账号:', this.userInfo.account);
                
                const result = await uniCloud.callFunction({
                    name: 'orderManage',
                    data: {
                        body: JSON.stringify({
                            action: 'getByStatus',
                            account: this.userInfo.account,
                            status: status // 状态值：pending(待付款)、unpaid(待发货)、shipping(已发货)、received(已收货)、completed(已完成)、cancelled(已取消)
                        })
                    }
                });
                
                console.log('获取订单结果:', result);
                
                if (result.result && result.result.status === 1) {
                    // 确保返回的是数组
                    const orders = Array.isArray(result.result.data) ? result.result.data : [];
                    console.log('处理后的订单数据:', orders);
                    return orders;
                } else {
                    console.error('获取订单失败:', result.result?.message);
                    return [];
                }
            } catch (error) {
                console.error('获取订单异常:', error);
                return [];
            }
        },
        
        // 添加订单到本地
        addOrder(orderData) {
            // 如果订单ID已存在，则更新该订单
            const existingIndex = this.orders.findIndex(order => order.id === orderData.id);
            
            if (existingIndex >= 0) {
                this.orders[existingIndex] = { ...this.orders[existingIndex], ...orderData };
            } else {
                // 否则添加新订单
                this.orders.unshift(orderData);
            }
            
            // 按照创建时间排序，最新的排在最前面
            this.orders.sort((a, b) => b.createTime - a.createTime);
            
            // 保存到本地存储
            uni.setStorageSync('orders', this.orders);
            
            // 如果是已支付的订单，触发购物车清空
            if (orderData.status === 'paid') {
                uni.$emit('orderPaid', { orderId: orderData.id });
            }
            
            return orderData;
        },
        
        // 添加地址
        addAddress(address) {
            // 生成唯一ID
            const newAddress = {
                ...address,
                id: Date.now().toString()
            };
            
            // 如果设为默认地址，需要将其他地址设为非默认
            if (newAddress.isDefault) {
                if (!this.userInfo.addresses) {
                    this.userInfo.addresses = [];
                }
                
                this.userInfo.addresses.forEach(addr => {
                    addr.isDefault = false;
                });
            }
            
            // 如果这是第一个地址，自动设为默认
            if (!this.userInfo.addresses || this.userInfo.addresses.length === 0) {
                newAddress.isDefault = true;
            }
            
            // 添加到地址列表
            if (!this.userInfo.addresses) {
                this.userInfo.addresses = [newAddress];
            } else {
                this.userInfo.addresses.unshift(newAddress);
            }
            
            // 保存到本地
            this.updateUserInfoLocal({ addresses: this.userInfo.addresses });
            
            return newAddress;
        },
        
        // 更新地址
        updateAddress(address) {
            if (!this.userInfo.addresses) {
                this.userInfo.addresses = [];
                return null;
            }
            
            const index = this.userInfo.addresses.findIndex(addr => addr.id === address.id);
            if (index === -1) return null;
            
            // 如果设为默认地址，需要将其他地址设为非默认
            if (address.isDefault) {
                this.userInfo.addresses.forEach(addr => {
                    addr.isDefault = false;
                });
            }
            
            // 更新地址
            this.userInfo.addresses[index] = { ...address };
            
            // 保存到本地
            this.updateUserInfoLocal({ addresses: this.userInfo.addresses });
            
            return this.userInfo.addresses[index];
        },
        
        // 删除地址
        deleteAddress(addressId) {
            if (!this.userInfo.addresses) return false;
            
            const index = this.userInfo.addresses.findIndex(addr => addr.id === addressId);
            if (index === -1) return false;
            
            // 如果删除的是默认地址，需要设置新的默认地址
            const wasDefault = this.userInfo.addresses[index].isDefault;
            
            // 删除地址
            this.userInfo.addresses.splice(index, 1);
            
            // 如果删除的是默认地址且还有其他地址，将第一个地址设为默认
            if (wasDefault && this.userInfo.addresses.length > 0) {
                this.userInfo.addresses[0].isDefault = true;
            }
            
            // 保存到本地
            this.updateUserInfoLocal({ addresses: this.userInfo.addresses });
            
            return true;
        },
        
        // 获取默认地址
        getDefaultAddress() {
            if (!this.userInfo.addresses || this.userInfo.addresses.length === 0) {
                return null;
            }
            
            // 查找默认地址
            const defaultAddress = this.userInfo.addresses.find(addr => addr.isDefault);
            
            // 如果没有设置默认地址，返回第一个地址
            return defaultAddress || this.userInfo.addresses[0];
        }
    },
    
    getters: {
        getUserScore: (state) => state.userInfo.score,
        getUsername: (state) => state.userInfo.user_name,
        getIsLoggedIn: (state) => state.isLoggedIn
    }
}); 